<template>
  <section>
    <div v-wechat-title="pageTitle" v-if="pageTitle"></div>
    <van-sticky>
      <PageHeader :title="pageTitle"/>
    </van-sticky>

    <template v-if="activity">
      <div class="pd10 bg-color-white">
        <div class="activity-detail" v-html="activity.detail"></div>
      </div>

      <div class="empty-box"></div>
      <div class="pd10 join-btn-wrapper">
        <van-button block round type="info" @click="onJoinClick">{{ activity.join_btn_label }}</van-button>
      </div>

      <van-overlay :show="joinWrapperVisible" @click="joinWrapperVisible=false">
        <div class="flex flex-col flex-center marketing-activity-join-wrapper" @click.stop>
          <div class="flex flex-col bg-color-white round-box" style="width: 60%;">
            <div class="flex flex-col flex-center pd20">
              <div class="flex flex-row flex-center font-large strong">参与要求</div>
              <div class="flex flex-row flex-left pt10 font-big" v-html="activity.apply_requirement_desc"></div>
            </div>

            <div class="flex flex-row flex-center pt10 pb10 font-common color-white bg-color-green"
                 style="border-bottom-left-radius: 8px;border-bottom-right-radius: 8px;"
              @click="onJoin">
              {{activity.join_btn_label}}
            </div>
          </div>
          <div class="flex flex-row flex-center pd20">
            <i class="iconfont icon-guanbi" style="font-size: 34px; color: #FFFFFF;"
               @click="joinWrapperVisible=false"/>
          </div>
        </div>
      </van-overlay>

      <van-overlay :show="subscribeOverlayVisible" @click="subscribeOverlayVisible=false">
        <div class="flex flex-col flex-center" style="height: 100%;">
          <div class="pd20 round-box bg-color-white">
            <div class="text-center">
              {{APP_NAME}}
            </div>

            <div class="text-center mt10">
              <img :src="STATIC_BASE_URL + 'images/mp/qrcode.jpg'" height="200" width="200" />
            </div>

            <div class="text-center mt5 font-big">
              长按二维码关注公众号
            </div>
          </div>

          <div class="flex flex-row flex-center pd20">
            <i class="iconfont icon-guanbi" style="font-size: 34px; color: #FFFFFF;"
               @click="subscribeOverlayVisible=false"/>
          </div>
        </div>
      </van-overlay>
    </template>
  </section>
</template>

<script>
import PageHeader from "../componets/PageHeader";
import {
  STATIC_BASE_URL,
  marketingActivityInfoUri,
  wechatJsApiConfigUri,
  marketingActivityJoinUri, memberMyProfileUri
} from "../../common/api";
import util from "../../assets/js/util";
import {ERROR_REALNAME_AUTH_REQUIRED, ERROR_SUBSCRIBE_MP_REQUIRED} from "../../common/error";
import Vue from 'vue';
import {Dialog} from "vant";
Vue.use(Dialog);

export default {
  components: {
    PageHeader
  },
  data() {
    return {
      APP_NAME: APP_NAME,
      STATIC_BASE_URL: STATIC_BASE_URL,
      pageTitle: '活动',
      activity: null,
      joinWrapperVisible: false,
      subscribeOverlayVisible: false
    }
  },
  methods: {
    getJsApiConfig() {
      if(!isWxServiceEnable) {
        return;
      }
      const that = this;
      const url = wechatJsApiConfigUri + '?url=' + encodeURIComponent(window.location.href);
      this.$http.get(url).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.toast(msg);
        } else {
          wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: data.appId, // 必填，公众号的唯一标识
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature,// 必填，签名
            jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'updateAppMessageShareData', 'updateTimelineShareData', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'chooseWXPay'] // 必填，需要使用的JS接口列表
          });

          wx.ready(function () {
            that.wxReady = true;
            console.log('wx配置成功');
            that.updateShareData();
          });

          wx.error(function (res) {
            console.log('wx配置出错');
          });
        }
      }, response => {
        // error callback
      })
    },
    updateShareData() {
      if (isWxServiceEnable && this.wxReady && this.activity) {
        const title = this.activity.name;
        // const imgUrl = this.activity.img_url;
        const imgUrl = STATIC_BASE_URL + 'images/logo.png';
        const link = window.location.href;
        const desc = '线下相亲活动，助你快速脱单';

        wx.updateAppMessageShareData({
          title: title, // 分享标题
          desc: desc, // 分享描述
          link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: imgUrl, // 分享图标
          success: function () {
            // 设置成功
            console.log('updateAppMessageShareData');
          }
        });

        wx.updateTimelineShareData({
          title: title, // 分享标题
          link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: imgUrl, // 分享图标
          success: function () {
            // 设置成功
            console.log('updateTimelineShareData');
          }
        })
      }
    },
    onJoinClick() {
      if(!this.GLOBAL.userInfo) {
        this.$toast('请先登录');
        localStorage.setItem('referrer', '/marketing_activity?id=' + this.$route.query.id);
        this.$router.push({name: 'UserLogin'});
        return;
      }
      this.joinWrapperVisible = true;
    },
    onJoin() {
      const that = this;
      const url = marketingActivityJoinUri + '?activity_id=' + this.$route.query.id;
      this.$http.get(url).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          if(code == ERROR_SUBSCRIBE_MP_REQUIRED) {
            that.toast('请先关注公众号：'+APP_NAME+'');
            that.subscribeOverlayVisible = true;
          } else if(code == ERROR_REALNAME_AUTH_REQUIRED) {
            Dialog.confirm({
              message: '参加活动需完成实名认证',
              showConfirmButton: true,
              confirmButtonText: '去认证',
              showCancelButton: true,
              cancelButtonText: '放弃'
            }).then(() => {
              that.$router.push({name: 'MyAuthIndex'});
            }).catch(() => {
              // on cancel
            });
          } else {
            that.toast(msg);
          }
        } else {
          that.toast.success('参与成功');
          that.getMyProfile();
        }
      }, response => {
        // error callback
      })
    },
    getActivity() {
      const that = this;
      const url = marketingActivityInfoUri + '?id=' + this.$route.query.id;
      this.$http.get(url).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.toast(msg);
        } else {
          data.activity.apply_requirement_desc = data.activity.apply_requirement_desc.replaceAll('\n', '<br />');
          that.activity = data.activity;
          that.pageTitle = data.activity.name;
        }
      }, response => {
        // error callback
      })
    },
    getMyProfile() {
      const that = this;
      this.$http.get(memberMyProfileUri).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.toast(msg);
        } else {
          that.GLOBAL.memberProfile = data.member;
          that.$router.push({name: 'MyIndex'});
        }
      }, response => {
        // error callback
      })
    }
  },
  created: function () {
    const fromuid = window.localStorage.getItem('user_id') ? window.localStorage.getItem('user_id') : 0;
    let _href = window.location.href;
    if (isWxServiceEnable && _href.indexOf('&replace=1') <= -1) {
      window.location.replace(_href + '&replace=1&fromuid=' + fromuid);
    } else if (_href.indexOf('fromuid=') > -1) {
      const fromuidVar = util.getQueryVariable('fromuid');
      if(fromuid > 0 && fromuid != fromuidVar) {
        window.location.replace(_href.replace('fromuid=' + fromuidVar, 'fromuid=' + fromuid));
      }
    }
  },
  mounted: function () {
    this.getActivity();
    this.getJsApiConfig();
  }
}
</script>

<style scoped>
.activity-detail {
  margin: 0;
  padding: 0;
  font-size: 0
}

.activity-detail >>> img {
  max-width: 100%;
  height: auto;
}

.empty-box {
  height: calc(60px + env(safe-area-inset-bottom));
}

.join-btn-wrapper {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-bottom: calc(10px + env(safe-area-inset-bottom));
}

.marketing-activity-join-wrapper {
  height: 100%;
}
</style>
